package org.metasketch.editor.links;

import org.metasketch.diagram.javafx.graphics.BaseGraphic;
import org.metasketch.editor.toolbox.IPointCalculator;
import org.metasketch.graphics.Point;

public class LinkEndCalculator {

	public static Point getCoordinates(double x, double y,
			BaseGraphic baseGraphic, LinkEndOrientation orientation) {

		Point completePosition = baseGraphic
				.getCompleteCoordinatesThroughParent();

		if (baseGraphic instanceof IPointCalculator) {
			return getObjectCoordinates(x, y, completePosition.getX(),
					completePosition.getY(), (IPointCalculator) baseGraphic,
					orientation);
		} else

			return getCoordinates(x, y, completePosition.getX(),
					completePosition.getY(), baseGraphic.getWidth(),
					baseGraphic.getHeight(), orientation);

	}

	public static Point getCoordinates(double x, double y, double objectX,
			double objectY, double width, double height,
			LinkEndOrientation orientation) {

		Point point = new Point(0, 0);

		if (orientation == LinkEndOrientation.CENTER) {
			point.setX((int) (objectX + width / 2.0));
			point.setY((int) (objectY + height / 2.0));
		} else {

			if (x > objectX + width)
				x = objectX + width;
			else if (x < objectX)
				x = objectX;

			if (y > objectY + height)
				y = objectY + height;
			else if (y < objectY)
				y = objectY;

			point.setX((int) x);
			point.setY((int) y);

		}

		return point;

	}

	public static Point getObjectCoordinates(double x, double y,
			double objectX, double objectY, IPointCalculator pointCalculator,
			LinkEndOrientation orientation) {

		Point point = null;

		if (orientation == LinkEndOrientation.CENTER) {
			point = pointCalculator.getCenter();

		} else {
			point = pointCalculator.getClosestPoint((int) x, (int) y);
		}

		// point.setX((int) (point.getX() + objectX));
		// point.setY((int) (point.getY() + objectY));

		return point;

	}

}
